import tornado
import tornado.web
import tornado.websocket
conndict={}
userlist=[]
class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = str(self.get_query_argument("userid"))
        name = str(self.get_query_argument("name"))
        #存储链接
        conndict[id] = self
        index = id.find("kefu")
        if index >= 0:
            # 判断是否为客服，如果为客服返回userlist
            self.write_message({"code": 200,"userlist": userlist, "mes": {}})
        else:
            # 判断是否为用户，如果为用户加入userlist
            userlist.append({"id": id,"name": name})
            # 用户上线
            key = "levelmes"+str(id)
            mm = r.get_str(key)
            if mm:
                mm = mm.decode()
                self.write_message({"code":200,"userlist":userlist,"mes": mm})
        print(conndict)
        print(userlist)

    #接收消息
    def on_message(self,mes):
        print(mes)
        mes = json.loads(mes)
        id = str(mes["id"])
        mes = mes["mes"]
        # 如果客服给用户发，判断用户是否在线，如果不在线将消息存入redis key:用户id+" evelmes",value:[]
        if id in conndict:
            conndict[id].write_message({"code": 200, "mes": mes, "userlist": userlist})
        else:
            # 存入redis
            key = "levelmes"+str(id)
            # 用户不在，把消息存入redis
            r.set_str(key, mes)

    def on_close(self):
        pass


from util.myredis import r
from db import db
import time, json
class TTHandler(tornado.web.RequestHandler):
    def get(self):
        id = int(self.get_query_argument('id'))
        while True:
            web = r.get_str('key')
            print(web)
            if web:
                key = int(web.decode())
                sql = "select * from wendu"
                res = db.find_all(sql)
                print(res)
                list = []
                for i in res:
                    if i['min'] <=key<=i['max']:
                        status = 1
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'key':key})
                    else:
                        status = 0
                        list.append({'id': i['id'], 'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'key':key})
                time.sleep(3)
                conndict[id].write_message(json.dumps(list))
